package com.dyzs.client;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.dyzs.util.Constants;
import com.dyzs.util.WSUtils;

public class ExchangeClient {


	public String update() throws Exception {
		Map<String, Object> params = new TreeMap<String, Object>();
//		params.put("in0", cc);			
		try {
			String resultXml = WSUtils.callWS("getExchange",params, Constants.ToolURL);			
			return resultXml;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}


	
	
	public Map<String ,Object> pullXml(String resultXml) throws Exception {		
		if(resultXml.equals("W")){
			throw new Exception("服务端异常！");
		}else{
			List<Map<String,Object>> list=null;
			Map<String,Object> fatherMap =null;
			Map<String, Object> map = null;
			try {
				ByteArrayInputStream bin = new ByteArrayInputStream(resultXml.getBytes());
				InputStreamReader in = new InputStreamReader(bin);
				XmlPullParser parser = Xml.newPullParser();
				parser.setInput(in);
				int event = parser.getEventType();
				while (event != XmlPullParser.END_DOCUMENT) {				
					switch (event) {
						case XmlPullParser.START_DOCUMENT:						
							fatherMap=new HashMap<String,Object>();						
							break;					
						case XmlPullParser.START_TAG:						
							if("lists".equals(parser.getName())){
								list=new ArrayList<Map<String,Object>>();
							}
							else if("item".equals(parser.getName())){
								map = new HashMap<String, Object>();
							}else							
								if ("bz".equals(parser.getName())) {
									map.put("bz", parser.nextText());
								} else if ("first".equals(parser.getName())) {
									map.put("first", "现汇买入价:"+parser.nextText());
								}else if ("second".equals(parser.getName())) {
									map.put("second", "现钞买入价:"+parser.nextText());
								} else if ("third".equals(parser.getName())) {
									map.put("third", "卖出价:"+parser.nextText());
								} else if ("fouth".equals(parser.getName())) {
									map.put("fouth", "中间价:"+parser.nextText());
								} else if ("title".equals(parser.getName())) {
									fatherMap.put("title",parser.nextText());
								} 						
							break;
						case XmlPullParser.END_TAG:
							if ("item".equals(parser.getName())) {							
								list.add(map);						
								map = null;						
							}else if("lists".equals(parser.getName())) {													
								fatherMap.put("list", list);						
							}
							break;
						}
					event = parser.next();
				}

			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("解析失败！", e);
			}
			return fatherMap;
		}
	}
}
